package com.hkyp.ss.coursewebadmin.controller;

import com.hkyp.ss.course.apis.CourseBackService;
import com.hkyp.ss.course.apis.DictionaryService;
import com.hkyp.ss.course.apis.NavigationItemService;
import com.hkyp.ss.course.apis.dto.common.PageReq;
import com.hkyp.ss.course.apis.dto.common.PageResp;
import com.hkyp.ss.course.apis.dto.request.CourseDTO;
import com.hkyp.ss.course.apis.dto.request.HomePageCourseDTO;
import com.hkyp.ss.course.apis.dto.response.CourseBackVO;
import com.hkyp.ss.course.apis.dto.response.DictionaryResponseDTO;
import com.hkyp.ss.course.apis.dto.response.FirstCommentVO;
import com.hkyp.ss.course.apis.enumu.DicTypeEnum;
import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.course.apis.utils.BeanMapper;
import com.hkyp.ss.coursewebadmin.dto.base.ResultBean;
import com.hkyp.ss.coursewebadmin.dto.request.BatchActionCourseDTO;
import com.hkyp.ss.coursewebadmin.dto.request.WebCourseDTO;
import com.hkyp.ss.coursewebadmin.dto.request.WebHomePageCourseDTO;
import com.hkyp.ss.coursewebadmin.dto.response.WebSourcePlatformDTO;
import com.hkyp.ss.coursewebadmin.utils.OSSUtil;
import com.hkyp.ss.coursewebadmin.utils.UserSessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

@Api(description = "课程后台管理")
@Slf4j
@RestController
@RequestMapping(value = "/a/b/")
public class CourseBackController {


    @Reference(version = "1.0")
    private CourseBackService courseBackService;

    @Reference(version = "1.0")
    private NavigationItemService navigationItemService;

    @Reference(version = "1.0")
    private DictionaryService dictionaryService;

    /**
     * 导航栏节点列表
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "导航分类")
    @RequestMapping(value = "/NavigationItem/list", method = RequestMethod.GET)
    public ResultBean getNavigationItemList(){

        return new ResultBean<>(navigationItemService.getAllNavigationItemList());

    }
    /**
     * 批量或单个课程上下架
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "批量或单个课程上下架 0:上架;1:下架")
    @RequestMapping(value = "/course/upOrdown/{action}", method = RequestMethod.PUT)
    public ResultBean<PageResp<FirstCommentVO>> upOrDownCourses(@Valid @RequestBody BatchActionCourseDTO actionCourseDTO, @PathVariable Integer action){

        int i = courseBackService.changeState(actionCourseDTO.getCids(), action);
        log.info("修改个数：{}",i);
        return new ResultBean<>();

    }

    /**
     * 推荐课程
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "推荐课程  0:取消推荐;1:推荐")
    @RequestMapping(value = "/course/recommend/{action}", method = RequestMethod.PUT)
    public ResultBean<PageResp<FirstCommentVO>> recommendCourses(@Valid @RequestBody BatchActionCourseDTO actionCourseDTO, @PathVariable Integer action){
        int i = courseBackService.recommendCourse(actionCourseDTO.getCids(), action);
        log.info("修改个数：{}",i);
        return new ResultBean<>();
    }

    /**
     * 删除课程
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "删除课程(批量或单个)  1:执行删除")
    @RequestMapping(value = "/course/{action}", method = RequestMethod.DELETE)
    public ResultBean<PageResp<FirstCommentVO>> deleteCourses(@Valid @RequestBody BatchActionCourseDTO actionCourseDTO, @PathVariable Integer action){
        int i = courseBackService.deleteCourses(actionCourseDTO.getCids(), action);
        log.info("删除个数：{}",i);
        return new ResultBean<>();
    }

    /**
     * 课程列表
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "带条件课程列表  ",notes = " recommend:1为推荐，0或null为非推荐；status:0上架，1下架")
    @RequestMapping(value = "/course", method = RequestMethod.GET)
    public ResultBean<PageResp<CourseBackVO>> getCoursesByConditions(WebHomePageCourseDTO homePageCourseDTO, PageReq pageReq){
        PageResp<CourseBackVO> courseBackVOPageResp = courseBackService.selectCourseByPage(BeanMapper.map(homePageCourseDTO, HomePageCourseDTO.class), pageReq);


       // navigationItemService
        return new ResultBean<>(courseBackVOPageResp);
    }

    /**
     * 新增课程
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新增课程  ")
    @RequestMapping(value = "/course", method = RequestMethod.POST)
    public ResultBean addCourse(@RequestBody  WebCourseDTO webCourseDTO ){
        courseBackService.saveCourse(BeanMapper.map(webCourseDTO, CourseDTO.class),1L);
        return new ResultBean<>( );
    }

    /**
     * 课程平台下拉框
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "课程平台下拉框  ")
    @RequestMapping(value = "/course/sourcePlatform", method = RequestMethod.GET)
    public ResultBean getCoursePlatform(){
        List<DictionaryResponseDTO> dictionarys = dictionaryService.getDictionaryByType(DicTypeEnum.SOURCE_PLATFORM.getCode());
        if(CollectionUtils.isEmpty(dictionarys)){
            return new ResultBean<>(new ArrayList<>());
        }
        return new ResultBean<>(BeanMapper.mapList(dictionarys,WebSourcePlatformDTO.class));
    }
    /**
     * 编辑课程
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "编辑课程  ")
    @RequestMapping(value = "/course/{courseId}", method = RequestMethod.PUT)
    public ResultBean putCourse(@RequestBody WebCourseDTO webCourseDTO, @PathVariable Long courseId){
        CourseDTO courseDTO = BeanMapper.map(webCourseDTO, CourseDTO.class);
        courseDTO.setId(courseId);
        courseBackService.updateCourse(courseDTO,1L);
        return new ResultBean<>( );
    }

    /**
     * 课程详情
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "课程详情  ")
    @RequestMapping(value = "/course/{courseId}", method = RequestMethod.GET)
    public ResultBean<CourseDTO> getCourse( @PathVariable Long courseId){

        CourseDTO courseDTO = courseBackService.selectCourseById(courseId);
        return new ResultBean<>( courseDTO);
    }



    /************************************* 上传头像 ********************************************************/
    @ApiOperation(value = "后台上传图片")
    @RequestMapping(value = "/api/common/upload", method = RequestMethod.POST)
    public ResultBean getUpload(Model model, HttpServletRequest request,
                                @RequestParam(value = "description",required=false) String description,
                                @RequestParam("file") MultipartFile file)throws Exception
    {
        System.out.println(description);
        long userId = UserSessionUtils.getUserId();
        return new ResultBean<>(upload(file,userId));
    }

    public String upload(MultipartFile file, Long userId) {
        //如果文件不为空，写入上传路径
        if(file.isEmpty()){
            throw new UnacceptableException("传入文件为空");
        }
        ;
        String filename = file.getOriginalFilename();
        // 在拦截器里，将JWT里的内容解析成对象，并放到了request里
        /***
         * substring(int beginIndex)
         * 返回一个新的字符串，它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始，直到此字符串末尾。
         *
         * 比如 001.png  以下代码得到  .png
         */
        String suffix=filename.substring(filename.lastIndexOf("."));
        ;
        String key = OSSUtil.getImgKey(userId+"",suffix);
        log.info("图片路径(key):"+key);
        OSSUtil.upload(file,key);

        //String link = OSSUtil.getImgUrlPrivate(key);
        String link = OSSUtil.getImgUrlNaked(key);
        log.info("获得访问链接(图片)："+link);

        return link;


    }

}
